package com.caowei.weicimpress.weicimpress;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.lingala.zip4j.util.Zip4jUtil;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by caoweiPc on 2014/7/23.
 */
public class ZipFileHandler extends AbstractFileHandler {
    private final static String TAG=ZipFileHandler.class.getSimpleName();
    private static final String ZIPHEAD="504B0304";
    private List<String> contained=new ArrayList<String>();
    public ZipFileHandler(Context context) {
        super(context);
        nameOfFormat="zip";
        deflate_method.put(Zip4jConstants.DEFLATE_LEVEL_NORMAL,"正常");
        deflate_method.put(Zip4jConstants.DEFLATE_LEVEL_FAST,"快速");
        deflate_method.put(Zip4jConstants.DEFLATE_LEVEL_FASTEST,"最快");
        deflate_method.put(Zip4jConstants.DEFLATE_LEVEL_MAXIMUM,"最大");
        deflate_method.put(Zip4jConstants.DEFLATE_LEVEL_ULTRA,"最好");
    }


    @Override
    protected MyDataList listfiles(FileInfoBean fileInfoBean) {
        contained.clear();
        File rootFile=fileInfoBean.getRootFile();
        MyDataList myDataList=new MyDataList();
        String parentPath=(!TextUtils.isEmpty(fileInfoBean.getParentPath())
                &&!fileInfoBean.getParentPath().equals(File.separator))?fileInfoBean.getParentPath():
                File.separator;
        ZipFile zipFile=null;
        myDataList.setParentPath(parentPath);
        try{
            zipFile=new ZipFile(rootFile);
            zipFile.setFileNameCharset("GBK");
            List<FileHeader> fhes=zipFile.getFileHeaders();
            Collections.sort(fhes, new Comparator<FileHeader>() {
                @Override
                public int compare(FileHeader lhs, FileHeader rhs) {
                    return lhs.getFileName().compareTo(rhs.getFileName());
                }
            });

            for(FileHeader fh:fhes){
                if(Utils.DEBUG){
                    Log.d(TAG,fh.getFileName());
                }
                String fileName=Utils.drop2SlashOfStr(fh.getFileName());
                String parentPath1=Utils.drop2SlashOfStr(parentPath);
                if(TextUtils.isEmpty(parentPath1)){
                    String fileNameSplit[]=fileName.split(File.separator);
                    if(!contained.contains(fileNameSplit[0])){
                         addToDataList(fh,fhes,rootFile,fileNameSplit,myDataList);
                         contained.add(fileNameSplit[0]);
                     }
                   // addToDataList(fh,fhes,rootFile,fileNameSplit,myDataList);
                    //todo
                 /*   if(fileNameSplit.length==1){
                        addToDataList(fh,fhes,rootFile,fileNameSplit,myDataList);
                    }else{

                    }*/
                }else if(fileName.startsWith(new StringBuilder(parentPath1).append(File.separator).toString())
                        &&!fileName.equals(parentPath1)){
                    String fileName1=fileName.substring(parentPath1.length()+1);
                    String fileNameSplit[]=fileName1.split(File.separator);

                    StringBuilder sb=new StringBuilder(parentPath1);
                    sb.append(File.separator).append(fileNameSplit[0]);
                    String str=Utils.normalizePath(sb.toString());
                    if(!contained.contains(str)){
                        addToDataList(fh,fhes,rootFile,fileNameSplit,myDataList);
                        contained.add(str);
                    }

                    /*
                    if(fileNameSplit.length==1){
                        addToDataList(fh,fhes,rootFile,fileNameSplit,myDataList);
                    }else{

                    }*/
                }
            }
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
                Log.e(TAG,"文件不合法");
            }
            throw new MyException("文件不合法",e,MyException.COMPRESSFILEDAMAGE);
        } finally {

        }
        return myDataList;
    }

    @Override
    public boolean isSurpportCryptogram() {
        return true;
    }

    @Override
    public boolean isSplite(File rootFile) {
        try {
            ZipFile zipFile=new ZipFile(rootFile);
            return  zipFile.isSplitArchive();
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
            }
            return false;
        }
    }

    @Override
    public boolean delete(List<FileInfoBean> beans,char[] passwd) {
        //todo
        FileInfoBean bean=beans.get(0);
        File rootFile=bean.getRootFile();
        String cachDirPath=MyApplication.getMyApplication().
                getApplicationContext().
                getCacheDir().
                getAbsolutePath();
        StringBuilder tempSb=new StringBuilder(cachDirPath);
        tempSb.append(File.separator).append("temp-").append(System.currentTimeMillis()).
                append(File.separator);
        File tempDir=new File(Utils.normalizePath(tempSb.toString()));
        ZipFile zipFile= null;
        List<String> beanNames=new ArrayList<String>();
        for(FileInfoBean bean1:beans){
            StringBuilder sb=new StringBuilder(bean1.getParentPath());
            sb.append(File.separator).append(bean1.getFileName());
            String name=Utils.normalizePath(sb.toString());
            name=Utils.dropHeadStr(name,File.separator);
            if(!bean1.isDir()){
                name=Utils.dropTailStr(name,File.separator);
            }
            beanNames.add(name);
        }
        try {
            zipFile = new ZipFile(rootFile);
            zipFile.setFileNameCharset("GBK");
            if(zipFile.isEncrypted()){
                zipFile.setPassword(passwd);
                if(Utils.DEBUG){
                    Log.d(TAG,"password="+String.valueOf(passwd));
                }
            }
            /*List<FileHeader> fhes=zipFile.getFileHeaders();
            for(FileHeader fh:fhes){
                for(String name:beanNames){
                    if(!fh.getFileName().startsWith(name)){
                        zipFile.extractFile(fh,tempDir.getAbsolutePath());
                    }
                }
            }*/
            zipFile.extractAll(tempDir.getAbsolutePath());
            //todo test
            if(Utils.DEBUG){
                Log.d(TAG,"================DEBUG1=================");
                tempDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        Log.d(TAG,dir.getAbsolutePath()+File.separator+filename);
                        return true;
                    }
                });
                Log.d(TAG,"===============DEBUG1==================");
            }
            //todo 删除
            for(String name:beanNames){
                StringBuilder sb=new StringBuilder(tempDir.getAbsolutePath());
                sb.append(File.separator).append(name);
                String fileName=Utils.dropTailStr(Utils.normalizePath(sb.toString()), File.separator);
                File file=new File(fileName);
                if(file.exists()){
                    Utils.del(file.getAbsolutePath());
                }
            }

            //todo test
            if(Utils.DEBUG){
                Log.d(TAG,"================DEBUG2=================");
                tempDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        Log.d(TAG,dir.getAbsolutePath()+File.separator+filename);
                        return true;
                    }
                });
                Log.d(TAG,"===============DEBUG2==================");
            }

            //再压缩
            StringBuilder sb=new StringBuilder(rootFile.getParent());
            sb.append(File.separator).
                    append(rootFile.getName()).
                    append("-temp-").
                    append(System.currentTimeMillis());
            String tempName=Utils.normalizePath(sb.toString());
            tempName=Utils.drop2Str(tempName,File.separator);
            File file1=new File(tempName);
            final ZipFile zipFile1=new ZipFile(file1);
            zipFile1.setFileNameCharset("GBK");
            //todo  暂时吧  原压缩包的信息考虑传进来
            final ZipParameters parameters=new ZipParameters();
            if(zipFile.isEncrypted()){
                parameters.setEncryptFiles(true);
                parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
                parameters.setPassword(passwd);
            }

            tempDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    try{
                        if(pathname.isDirectory()){
                            zipFile1.addFolder(pathname,parameters);
                        }else{
                            zipFile1.addFile(pathname,parameters);
                        }
                    } catch (ZipException e) {
                        e.printStackTrace();
                        throw  new MyException("删除出错了",MyException.ERROR);
                    }
                    return true;
                }
            });
            if(rootFile.exists()){
                Utils.del(rootFile.getAbsolutePath());
            }
            file1.renameTo(rootFile);
            return true;
        } catch (ZipException e) {
           if(Utils.DEBUG){
               e.printStackTrace();
           }
            if(e.getMessage().contains("Wrong password")||e.getMessage().contains("Wrong Password?")){
                throw new MyException("Wrong password!",MyException.FAIL_EXTRACT_BYPASSWDERROR);
            }
            throw new MyException("zip文件已损坏!",MyException.COMPRESSFILEDAMAGE);
        }finally {
            if(tempDir.exists()){
                Utils.del(tempDir.getAbsolutePath());
            }
        }

/*
        try {
            ZipFile zipFile=new ZipFile(rootFile);
            zipFile.setFileNameCharset("GBK");
            StringBuilder sb=new StringBuilder(bean.getParentPath());
            sb.append(File.separator).append(bean.getFileName());
            String path=Utils.dropHeadStr(Utils.normalizePath((sb.toString())),File.separator);
            if(!bean.isDir()){
                path=Utils.dropTailStr(path,File.separator);
            }
            if(zipFile.isEncrypted()){
                zipFile.setPassword(bean.getPasswd());
            }
            if(bean.isDir()){
                List<FileHeader> list=zipFile.getFileHeaders();
                Collections.sort(list, new Comparator<FileHeader>() {
                    @Override
                    public int compare(FileHeader lhs, FileHeader rhs) {
                        return lhs.getFileName().compareTo(rhs.getFileName());
                    }
                });
                int currentIndex=list.indexOf(zipFile.getFileHeader(path));
                List<FileHeader> removeFileHeaders=new ArrayList<FileHeader>();
                removeFileHeaders.addAll(list.subList(currentIndex+1,list.size()));
                for(int i=removeFileHeaders.size()-1;i>=0;i--){
                    FileHeader fileHeader=removeFileHeaders.get(i);
                    if(fileHeader.getFileName().startsWith(path)){
                        FileHeader fh= zipFile.getFileHeader(fileHeader.getFileName());
                        if(fh!=null){
                            zipFile.removeFile(fh);
                        }
                    }
                }
            }
            FileHeader fh= zipFile.getFileHeader(path);
            if(fh!=null){
                zipFile.removeFile(path);
            }
            //todo
            //zipFile.removeFile(path);
            return true;
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
                throw new MyException("压缩文件已损坏",e,MyException.COMPRESSFILEDAMAGE);
            }
            return false;
        }*/
    }

    @Override
    public void batchRenamePartsByMainFile(MainPartFile mainPartFile) {
        if(mainPartFile.partFiles!=null&&!mainPartFile.partFiles.isEmpty()){
            List<String> resultParts=new ArrayList<String>();
            for(String file:mainPartFile.partFiles){
                if(file.startsWith(mainPartFile.getMainFile().getParent())&&file.endsWith("."+getNameOfFormat())){
                    resultParts.add(file);
                    break;
                }
                int index= file.lastIndexOf(".");
                String fxt=file.substring(index, file.length());
                String fpre=mainPartFile.mainFile.getName().substring(
                        0, mainPartFile.mainFile.getName().lastIndexOf("."));
                String dirStr=mainPartFile.getMainFile().getParent();
                File file1=new File(Utils.normalizePath(dirStr+ File.separator+fpre+fxt));
                if(file1.exists()){
                    Utils.del(file1.getAbsolutePath());
                }
                (new File(file)).renameTo(file1);
                resultParts.add(file1.getAbsolutePath());
            }
            mainPartFile.partFiles=resultParts;
        }
    }

    private void addToDataList(FileHeader fh,
                               List<FileHeader> fhes,
                               File rootFile,
                               String fileNameSplit[],
                               MyDataList myDataList){
        FileInfoBean bean=new FileInfoBean();
        bean.setDir(fh.isDirectory());
        bean.setIcoId(R.drawable.fileico);
        bean.setRootFile(rootFile);
        long lastModFileTime=fh.getLastModFileTime();
        long rootFileModfyTime=rootFile.lastModified();
        lastModFileTime=lastModFileTime<=rootFileModfyTime?rootFileModfyTime:lastModFileTime;
        StringBuilder sb=new StringBuilder(Utils.formateDate(lastModFileTime,
                Utils.DEFAULTDATEPATTERNNOTWITHMMSS));
        sb.append(" ").append(fh.isDirectory()?"d":"f");
        bean.setDate_authrity(sb.toString());
        bean.setLastModFileTime(fh.getLastModFileTime());

        if(fileNameSplit.length>1||fh.isDirectory()){
            bean.setDir(true);
            bean.setIcoId(R.drawable.diricocontent);
            int numOfDirs= myDataList.getNumOfDirs()==-1?0:myDataList.getNumOfDirs();
            myDataList.setNumOfDirs(++numOfDirs);
            int currentIndex= fhes.indexOf(fh);
            List<String> temps=new ArrayList<String>();
            StringBuilder sb1=new StringBuilder(myDataList.getParentPath());
            sb1.append(File.separator).append(fileNameSplit[0]);
            String str1=Utils.dropHeadStr(Utils.normalizePath(sb1.toString()),File.separator);
            for(int i=currentIndex+1;i<fhes.size();i++){
                FileHeader fh1=fhes.get(i);
                String name= fh1.getFileName();
                if(name.startsWith(str1)){
                    String name1= Utils.drop2Str(name.substring(str1.length()),File.separator);
                    int firstSlashIndex= name1.indexOf(File.separator);
                    if(firstSlashIndex>0){
                        name1=name1.substring(0,firstSlashIndex);
                    }
                    if(TextUtils.isEmpty(name1)){
                        break;
                    }
                    if(!temps.contains(name1)){
                        temps.add(name1);
                    }
                }else{
                    break;
                }
            }
            bean.setNumOfSubFile(temps.size());
        }else {
            bean.setSize(BigDecimal.valueOf(fh.getCompressedSize()));
            bean.setIcoId(R.drawable.fileico);
            int numOfFiles= myDataList.getNumOfFiles()==-1?0:myDataList.getNumOfFiles();
            myDataList.setNumOfFiles(++numOfFiles);
        }

      /*  if(fh.isDirectory()){
            bean.setIcoId(R.drawable.diricocontent);
            int numOfDirs= myDataList.getNumOfDirs()==-1?0:myDataList.getNumOfDirs();
            myDataList.setNumOfDirs(++numOfDirs);
            int currentIndex= fhes.indexOf(fh);
            List<String> temps=new ArrayList<String>();
            for(int i=currentIndex+1;i<fhes.size();i++){
                FileHeader fh1=fhes.get(i);
                String name= fh1.getFileName();
                if(name.startsWith(fh.getFileName())){
                    String name1= Utils.drop2Str(name.substring(fh.getFileName().length()),File.separator);
                    int firstSlashIndex= name1.indexOf(File.separator);
                    if(firstSlashIndex>0){
                        name1=name1.substring(0,firstSlashIndex);
                    }
                    if(TextUtils.isEmpty(name1)){
                        break;
                    }
                    if(!temps.contains(name1)){
                        temps.add(name1);
                    }
                }else{
                    break;
                }
            }
            bean.setNumOfSubFile(temps.size());
        }else{
            bean.setIcoId(R.drawable.fileico);
            int numOfFiles= myDataList.getNumOfFiles()==-1?0:myDataList.getNumOfFiles();
            myDataList.setNumOfFiles(++numOfFiles);
        }*/

        bean.setParentPath(myDataList.getParentPath());
        bean.setFileName(fileNameSplit[0]);
        bean.setCompressed(true);
        bean.setCompressFileHandler(this);
        myDataList.getFileInfoBeans().add(bean);

//        myDataList.setSizeOfCurrentDir(BigDecimal.valueOf(fh.getCompressedSize()));
    }

    @Override
    public boolean isThisHandler(File rootFile) {
        boolean result=false;
        if(rootFile!=null){
            ZipFile zipFile= null;
            try {
                zipFile = new ZipFile(rootFile);
                return zipFile.isValidZipFile();
            } catch (ZipException e) {
                if(Utils.DEBUG){
                    e.printStackTrace();
                    Log.e(TAG,"不是合法zip文件");
                }
                return false;
            }
          /*  result= zipFile.isValidZipFile();
            ByteBuffer byteBuffer= ByteBuffer.allocate(4);
            FileInputStream inf=null;
            FileChannel inChannel=null;
            try {
                inf = new FileInputStream(rootFile);
                inChannel=inf.getChannel();
                inChannel.read(byteBuffer);
                String hexStr= Utils.bytesToHexString(byteBuffer.array());
                result=hexStr.equalsIgnoreCase(ZIPHEAD)?true:false;
                if(!result){
                    ZipFile zipFile=new ZipFile(rootFile);
                    result= zipFile.isValidZipFile();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e(TAG,"文件没找到");
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG,"读取出错");
                return false;
            } catch (ZipException e) {
                e.printStackTrace();
                return false;
            } finally {
                if(inChannel!=null){
                    try {
                        inChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inf!=null){
                    try {
                        inf.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }*/
        }
        return result;
    }

    /*
    compress 到一个文件
    * */
    @Override
    public File subCompress(File saveFlie,String passwd,int compressmethod_key,List<FileInfoBean> beans) {
        //这里只针对系统目录里的文件压缩
        try {
            final ZipFile zipFile = new ZipFile(saveFlie);
            zipFile.setFileNameCharset("GBK");
            int compress_level=(compressmethod_key==-1||compressmethod_key==0)?
                    Zip4jConstants.DEFLATE_LEVEL_NORMAL:compressmethod_key;
            final ZipParameters parameters=new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(compress_level);

            if(!TextUtils.isEmpty(passwd)){
                parameters.setEncryptFiles(true);
                parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
                parameters.setPassword(passwd.toCharArray());
            }
            for(FileInfoBean bean:beans){
                File srcFile=new File(Utils.normalizePath(bean.getParentPath()+File.separator+
                        bean.getFileName()));
                if(srcFile.isDirectory()){
                    zipFile.addFolder(srcFile, parameters);
                }else{
                    zipFile.addFile(srcFile, parameters);
                }
            }
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
                Log.d(TAG,"压缩失败");
            }
            throw new MyException("压缩失败",e,MyException.FAIL_COMPRESS);
        }
        return saveFlie;
    }

    @Override
    public MainPartFile subCompress(File saveFile,
                              String passwd,
                              int compressmethod_key,
                              final List<FileInfoBean> beans,
                              int subsize, String unit) {
        String saveFilePath=saveFile.getAbsolutePath();
        String saveDirName=saveFilePath.substring(0,saveFilePath.lastIndexOf(File.separator));
        String saveFileName=saveFile.getName();
        final String saveFileNameWithNotSuffix=Utils.dropDotSuffix(saveFileName);
        String suffixPattern="(\\.z[0-9]+)$";
        final Pattern p=Pattern.compile(suffixPattern);
        File targetDir=new File(saveDirName);
        targetDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.isFile()){
                    String name=pathname.getName();
                    Matcher m=p.matcher(name);
                    if(m.find()){
                        if(name.startsWith(saveFileNameWithNotSuffix)){
                            Utils.del(pathname.getAbsolutePath());
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
        });

        try{
            ZipFile zipFile = new ZipFile(saveFile);
            zipFile.setFileNameCharset("GBK");
            int index= Arrays.binarySearch(Utils.UNITS, unit.toUpperCase());
            long subsize_B= (long) (Math.pow(Utils.SIZEUNIT,index)*subsize);

            int compress_level=(compressmethod_key==-1||compressmethod_key==0)?
                    Zip4jConstants.DEFLATE_LEVEL_NORMAL:compressmethod_key;
            ZipParameters parameters=new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(compress_level);

            if(!TextUtils.isEmpty(passwd)){
                parameters.setEncryptFiles(true);
                parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
                parameters.setPassword(passwd.toCharArray());
            }
            ArrayList<File> srcFiles=new ArrayList<File>();
            ArrayList<File> srcDirs=new ArrayList<File>();
            for(FileInfoBean bean:beans){
                File file=new File(Utils.normalizePath(bean.getParentPath()+File.separator+
                        bean.getFileName()));
                srcFiles.add(file);
               if(file.isDirectory()){
                    File dir=new File(
                            Utils.normalizePath(bean.getParentPath()+File.separator+
                                    bean.getFileName()));
                    List<File> files= Zip4jUtil.getFilesInDirectoryRec(dir,false);
                    srcFiles.addAll(files);
                    srcDirs.add(dir);
                }
            }
            if(srcDirs.size()>0){
                parameters.setDefaultFolderPath(srcDirs.get(0).getParent());
                parameters.setIncludeRootFolder(true);
            }
            if(subsize_B<=65536){
                zipFile.createZipFile(srcFiles, parameters);
            }else{
                zipFile.createZipFile(srcFiles, parameters, true, subsize_B);
            }
            MainPartFile mainPartFile=new MainPartFile();
            mainPartFile.mainFile=saveFile;
            mainPartFile.setPartFiles(zipFile.getSplitZipFiles());
            return mainPartFile;
        } catch (ZipException e){
            if(Utils.DEBUG){
                e.printStackTrace();
                Log.d(TAG,"压缩失败");
            }
            throw new MyException("压缩失败",e,MyException.FAIL_COMPRESS);
        }
    }

    @Override
    public File extractAll(File targetDir,FileInfoBean bean) {
            StringBuilder sb=new StringBuilder();
            sb.append(bean.getParentPath()).append(File.separator).append(bean.getFileName());
            String srcfileName= Utils.normalizePath(sb.toString());;
            if(!bean.isDir()){
                srcfileName=Utils.dropTailStr(srcfileName,File.separator);
            }
            File file=new File(srcfileName);
            File  target=new File(targetDir,Utils.dropDotSuffix(file.getName()));
            boolean success= target.mkdirs();
            if(!success){
                throw new MyException("解压出错",MyException.ERROR);
            }
            try {
                ZipFile zipFile=new ZipFile(file);
                zipFile.setFileNameCharset("GBK");
                if(zipFile.isEncrypted()){
                    zipFile.setPassword(bean.getPasswd());
                }
                zipFile.extractAll(target.getAbsolutePath());
            } catch (ZipException e) {
                if(Utils.DEBUG){
                    e.printStackTrace();
                    Log.d(TAG,"解压失败:"+e.getMessage());
                }
                Utils.del(target.getAbsolutePath());
                if(e.getMessage().contains("Wrong password")||e.getMessage().contains("Wrong Password?")){
                    throw new MyException("Wrong password!",MyException.FAIL_EXTRACT_BYPASSWDERROR);
                }
                throw new MyException("解压失败:"+e.getMessage(),e,MyException.ERROR);
            }
        return targetDir;
    }

    @Override
    public File extractItem(File targetDir, FileInfoBean bean) {
        File rootFile=bean.getRootFile();
        try {
            StringBuilder sb=new StringBuilder(bean.getParentPath());
            sb.append(File.separator).append(bean.getFileName());
            String fileName=Utils.dropHeadStr(Utils.normalizePath(sb.toString()), File.separator);
            if(!targetDir.exists()){
                boolean b= targetDir.mkdirs();
                if(!b){
                    throw new MyException(targetDir.getAbsolutePath()+"创建出错!",MyException.ERROR);
                }
            }
            if(!bean.isDir()){
                fileName=Utils.dropTailStr(fileName,File.separator);
            }
            ZipFile zipFile=new ZipFile(rootFile);
            zipFile.setFileNameCharset("GBK");
            if(zipFile.isEncrypted()){
                zipFile.setPassword(bean.getPasswd());
            }
            List<FileHeader> fileHeaders= zipFile.getFileHeaders();
            if(!bean.isDir()){
                zipFile.extractFile(fileName,targetDir.getAbsolutePath());
            }else{
                for(FileHeader fh:fileHeaders){
                    if(fh.getFileName().startsWith(fileName)){
                        zipFile.extractFile(fh,Utils.normalizePath(targetDir.getAbsolutePath()));
                    }
                    /*if(!fh.isDirectory()&&fh.getFileName().startsWith(fileName)&&!fh.getFileName().equals(fileName)){
                        zipFile.extractFile(fh,Utils.normalizePath(tempSb.toString()));
                    }*/
                }
            }
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
            }
            Utils.del(targetDir.getAbsolutePath());
            if(e.getMessage().contains("Wrong password")||e.getMessage().contains("Wrong Password?")){
                throw new MyException("Wrong password!",MyException.FAIL_EXTRACT_BYPASSWDERROR);
            }
            throw new MyException(e,MyException.ERROR);
        }
        return targetDir;
    }

    @Override
    public boolean isEncried(File file) {
        try {
            ZipFile zipFile=new ZipFile(file);
            return zipFile.isEncrypted();
        } catch (ZipException e) {
            if(Utils.DEBUG){
                e.printStackTrace();
            }
            throw new MyException("出错了，可能不是zip文件",e,MyException.ERROR);
        }
    }

}
